<template>
  <div>
    <el-button type="primary" @click="showAddUserDialog">添加用户</el-button>
    <el-button type="primary" @click="saveDeviceUsers">保存</el-button>
    <el-table :data="state.userList" style="width: 100%">
      <el-table-column prop="nickname" label="用户名"></el-table-column>
      <el-table-column prop="tel" label="手机号"></el-table-column>
      <el-table-column label="是否可操作">
        <template #default="{ row }">
          <el-switch
            v-model="row.editable"
            active-text="可操作"
            active-value="1"
            inactive-value="0"
            inactive-text="不可操作"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="{ row }">
          <el-button size="small" type="danger" @click="removeUser(row)"
            >移除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加用户对话框 -->
    <el-dialog v-model="state.addUserDialogVisible" title="添加用户">
      <el-table
        :data="unselectedUsers"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" column-key="id"></el-table-column>
        <el-table-column prop="nickname" label="用户名"></el-table-column>
        <el-table-column prop="tel" label="手机号"></el-table-column>
      </el-table>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="state.addUserDialogVisible = false"
            >取消</el-button
          >
          <el-button type="primary" @click="addUser">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { reactive, onMounted, watch } from "vue";
import { ElMessage } from "element-plus";
import {
  saveManyDeviceUsers,
  getDeviceUserListByDeviceId,
} from "@/api/system/deviceuser.js";
import { getAllUser } from "@/api/system/user.js";
const props = defineProps({
  deviceId: {
    type: String,
    default: "",
  },
});
const emit = defineEmits(["flushDeviceList", "closeDialog"]);
// 响应式数据
const state = reactive({
  userList: [],
  addUserDialogVisible: false,
  allUsers: [],
  multipleSelection: [],
});
const handleSelectionChange = (val) => {
  state.multipleSelection = val;
};
// 获取用户列表
const fetchUserList = async () => {
  try {
    const response = await getUserList(props.deviceId);
    state.userList = response;
  } catch (error) {
    console.error("获取用户列表失败:", error);
    ElMessage.error("获取用户列表失败，请稍后重试");
  }
};
// 保存设备关联的用户
const saveDeviceUsers = async () => {
  try {
    let deviceuserlist = state.userList.map((item) => ({
      deviceid: props.deviceId,
      editable: item.editable,
      userid: item.id,
    }));
    await saveManyDeviceUsers(props.deviceId, deviceuserlist);
    emit("flushDeviceList");
    emit("closeDialog");
    ElMessage.success("保存成功");
  } catch (error) {
    console.error("操作失败:", error);
    ElMessage.error("操作失败，请稍后重试");
  }
};
// 显示添加用户对话框
const showAddUserDialog = () => {
  state.addUserDialogVisible = true;
};
// 计算未选择用户列表
const unselectedUsers = computed(() => {
  const selectedUserIds = state.userList.map((user) => user.id);
  return state.allUsers.filter((user) => !selectedUserIds.includes(user.id));
});

const addUser = () => {
  state.userList.push(...state.multipleSelection);
  state.addUserDialogVisible = false;
};
// 移除用户
const removeUser = async (row) => {
  state.userList = state.userList.filter((user) => user.id !== row.id);
};
const getuserlists = (data) => {
  return getAllUser(data).then((response) => {
    state.allUsers = response;
  });
};
watch(
  () => props.deviceId,
  async (newDeviceId, oldDeviceId) => {
    getDeviceUserListByDeviceId(newDeviceId).then((response) => {
      state.userList = response;
    });
  }
);
onMounted(() => {
  getDeviceUserListByDeviceId(props.deviceId).then((response) => {
    state.userList = response;
  });
  getuserlists({});
});
</script>
